/**
 * 
 */
package org.andersonb.prototypes.jpa.entity;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.EntityTransaction;
import javax.persistence.TypedQuery;

/**
 * @author abernardo
 * 
 */
// @Repository("genericDAO")
// @Scope(value = ConfigurableBeanFactory.SCOPE_SINGLETON)
public class GenericJpaDAOImpl<T> implements GenericDAO<T> {

//	@PersistenceContext
	protected EntityManager em = JPAUtil.getEntityManager();

	/**
	 * {@inheritDoc}
	 */
	// @Transactional
	@Override
	public T save(T entity) {
		 EntityTransaction t = em.getTransaction();
		 t.begin();
		em.persist(entity);
		 t.commit();
		return entity;
	}

	/**
	 * {@inheritDoc}
	 */
	// @Transactional
	@Override
	public T update(T entity) {
		// EntityTransaction t = em.getTransaction();
		// t.begin();
		T result = em.merge(entity);
		// t.commit();
		return result;
	}

	/**
	 * {@inheritDoc}
	 */
	// @Transactional
	@Override
	public Boolean delete(Class<T> type, Object entityId) {
		// EntityTransaction t = em.getTransaction();
		// t.begin();
		T ref = em.getReference(type, entityId);
		em.remove(ref);
		// t.commit();

		return Boolean.TRUE;
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public T find(Class<T> type, Long entityId) {
		return em.find(type, entityId);
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public List<T> findAll(Class<T> type) {
		TypedQuery<T> q = em.createQuery("select t from " + type.getName(),
				type);
		return q.getResultList();
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public EntityManager getEntityManager() {
		return em;
	}

}
